import { Action, Selector, State, StateContext } from '@ngxs/store';
import { NzMessageService } from 'ng-zorro-antd/message';
import { PermissionDict } from '../../models/system/permission-dict.model';
import { CommonService } from '../../services/common.service';
import {
    DownloadFileAction,
    GetAllPermissionDictsAction,
    GetDifferentialCapacitanceCurveAction,
    GetIsSuperAdminAction
} from './common.action';
import { catchError, map } from 'rxjs/operators';
import { Injectable } from '@angular/core';
import { RoleModel } from '../../models/system/role.model';
import { StandardModel } from '../../models/common.model';

export interface CommonStateModel {
    roles: Array<RoleModel>;
    workTypes: Array<WorkerType>;
    permissionDicts: Array<PermissionDict>;
    standards: Array<StandardModel>;
    superAdminState: number;
    loadingState: boolean;
    modalLoadingState: boolean;
    payload: any;
    currentStorageId: string;
}

@State<CommonStateModel>({
    name: '_CommonState',
    defaults: {
        roles: [],
        workTypes: [],
        permissionDicts: [],
        standards: [],
        superAdminState: null,
        loadingState: false,
        modalLoadingState: false,
        payload: '',
        currentStorageId: ''
    }
})
@Injectable()
export class CommonState {
    constructor(private _commonService: CommonService, private _nzMessageService: NzMessageService) {}

    @Selector()
    public static roles(state: CommonStateModel) {
        return state.roles;
    }

    @Selector()
    public static workyTypes(state: CommonStateModel) {
        return state.workTypes;
    }

    @Selector()
    public static permissionDicts(state: CommonStateModel) {
        return state.permissionDicts;
    }

    @Selector()
    public static superAdminState(state: CommonStateModel) {
        return state.superAdminState;
    }

    @Selector()
    public static loadingState(state: CommonStateModel) {
        return state.loadingState;
    }

    @Selector()
    public static modalLoadingState(state: CommonStateModel) {
        return state.modalLoadingState;
    }


    @Selector()
    public static standards(state: CommonStateModel) {
        return state.standards;
    }


    /**
     * 获取所有权限字典
     * @param ctx 状态上下文
     * @param action 触发的动作
     */
    @Action(GetAllPermissionDictsAction)
    GetAllPermissionDicts(ctx: StateContext<CommonStateModel>, action: GetAllPermissionDictsAction) {
        return this._commonService.getAllPermissionDicts().pipe(
            map((res: any) => {
                ctx.patchState({
                    permissionDicts: res
                });
            })
        );
    }

    /**
     * 获取是否是超级管理员
     * @param ctx 状态上下文
     * @param action 触发的动作
     */
    @Action(GetIsSuperAdminAction)
    GetIsSuperAdminAction(ctx: StateContext<CommonStateModel>, action: GetIsSuperAdminAction) {
        const state = ctx.getState();
        ctx.setState({ ...state, superAdminState: action.superAdminState });
    }

    /**
     * 获取微分电容曲线
     * @param ctx 状态上下文
     * @param action 触发的动作
     */
    @Action(GetDifferentialCapacitanceCurveAction)
    GetDifferentialCapacitanceCurve(ctx: StateContext<CommonStateModel>, action: GetDifferentialCapacitanceCurveAction) {
        const formData = new FormData();
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        // @ts-ignore
        formData.append('file', action.file);
        formData.append('stepLength', action.step);
        formData.append('chargeDataId', action.chargeDataId);
        return this._commonService.getDifferentialCapacitanceCurve(formData).pipe(
            map((res: any) => {
                if (res.code === 200) {
                    ctx.patchState({
                        payload: res,
                    });
                }else {
                    ctx.patchState({
                        payload: {},
                    });
                    this._nzMessageService.error(res.msg);
                }
            }),
            catchError((error) => {
                throw new Error(error);
            })
        );
    }


    /**
     * 下载微分电容曲线
     * @param ctx 状态上下文
     * @param action 触发的动作
     */
    @Action(DownloadFileAction)
    DownloadFile(ctx: StateContext<CommonStateModel>, action: DownloadFileAction) {
        return this._commonService.downloadFile(action.url, action.fileName, action.parma, action.successCallback, action.errorCallback);
    }

}
